<template>

  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.context" placeholder="搜索" style="width: 200px;" class="filter-item"
        @keyup.enter.native="getList" />
      <el-select v-model="listQuery.importance" :placeholder="$t('table.importance')" clearable style="width: 90px"
        class="filter-item">
        <el-option v-for="item in importance" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-select v-model="listQuery.status" placeholder="状态" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in status" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="getList">
        {{ $t('table.search') }}
      </el-button>
    </div>

    <el-table v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%">
      <el-table-column align="center" label="ID" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column width="180px" align="center" label="最后更新时间">
        <template slot-scope="scope">
          <span>{{ scope.row.lastTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>

      <el-table-column class-name="status-col" label="状态" width="110">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">
            {{ row.status | chineseFilter }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column width="100px" label="重要性">
        <template slot-scope="scope">
          <svg-icon v-for="(n,i) in +scope.row.importance" :key="i" icon-class="star" class="meta-item__icon" />
        </template>
      </el-table-column>

      <el-table-column width="160px" align="center" label="评论">
        <template slot-scope="scope">
          <el-badge :value="scope.row.disComment" :max="99" class="item" :hidden="scope.row.disComment<=0">
            <el-popover ref="comment" placement="right" title="[管理] 评论" width="600" height="300" trigger="hover">
              <el-tooltip content="获取数据" placement="left" effect="dark" style="margin-right: 10px;">
                <el-button :loading="isInit" size="small" type="primary" icon="el-icon-refresh-right" @click="getComment(scope.row)">加载</el-button>
              </el-tooltip>
              <el-table
                  :data="scope.row.comments"
                  style="width: 100%"
                  max-height="250">
                  <el-table-column
                  fixed
                    label="评论"
                    width="150">

                    <template slot-scope="scope">
                      <el-badge value="new" :max="99" class="item" :hidden="scope.row.status>0">
                        <span style="margin-left: 10px">{{ scope.row.content}}</span>
                        </el-badge>
                      </template>

                  </el-table-column>
                  <el-table-column
                        label="日期"
                        width="180">
                        <template slot-scope="scope">
                          <i class="el-icon-time"></i>
                          <span style="margin-left: 10px">{{ scope.row.createTime | parseTime}}</span>
                        </template>
                      </el-table-column>
                      <el-table-column
                            label="状态"
                            width="120">
                            <template slot-scope="scope">
                              <i class="el-icon-question"></i>
                              <span style="margin-left: 10px">{{ scope.row.status==0?'待审核':'审核通过' }}</span>
                            </template>
                          </el-table-column>
                  <el-table-column
                    prop="fromUserName"
                    label="姓名"
                    width="120">
                  </el-table-column>
                  <el-table-column
                    fixed="right"
                    label="操作"
                    width="120">
                    <template slot-scope="scope">
                      <el-button v-if="scope.row.status<=0"
                        @click.native.prevent="publishedComment(scope.row)"
                        type="text"
                        size="small">
                        通过审核
                      </el-button>
                      <el-button
                        @click.native.prevent="deleteRow(scope.row)"
                        type="text"
                        size="small">
                        移除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
            </el-popover>
            <div v-popover:comment>
              <el-switch v-model="scope.row.comment" active-color="#13ce66" :active-value="Math.abs(scope.row.comment)"
                :inactive-value="-Math.abs(scope.row.comment)" inactive-color="#ff4949" @change="changeComment(scope.row)">
              </el-switch>
              <span>{{scope.row.comment>=0?"显示":"隐藏"}}</span>
              <span> {{Math.abs(scope.row.comment)}}条</span>
            </div>
         </el-badge>
        </template>
      </el-table-column>

      <el-table-column width="120px" align="center" label="阅读量">
        <template slot-scope="scope">
          <span>{{ scope.row.viewCount }}</span>
        </template>
      </el-table-column>

      <el-table-column label="标题" :fit="true">
        <template slot-scope="{row}">
          <router-link :to="'/example/edit/'+row.id" class="link-type">
            <span>{{ row.title }}</span>
          </router-link>
        </template>
      </el-table-column>

      <el-table-column label="概要">
        <template slot-scope="{row}">
          <span>{{ row.summary }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="300" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" icon="el-icon-edit" @click="detail(scope.row.id)">
            编辑
          </el-button>
          <el-button :type="scope.row.status!='published'?'info':'success'" size="mini"
            :icon="scope.row.status!='published'?'el-icon-document-remove':'el-icon-document-add'" @click="changeStatus(scope.row)">
            {{scope.row.status!='published'?'草稿':'发布'}}
          </el-button>
          <el-button type="danger" size="mini" icon="el-icon-delete" @click="beforeDelete(scope.row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.size"
      @pagination="getList" />
    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
      <span>删除文章后评论也会一起被删除</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="deleteDoc()" :icon="deleteLoading?'el-icon-loading':''" :disabled="deleteLoading">确 定</el-button>
      </span>
    </el-dialog>
  </div>

</template>

<script>
  import waves from '@/directive/waves' // waves directive
  import {
    fetchList,
    update,
    deleteDoc,
    getComment,
    publisdedComment,
    deleteComment
  } from '../../api/doc.js'
  import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

  export default {
    name: 'ArticleList',
    components: {
      Pagination
    },
    directives: {
      waves
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'info',
          deleted: 'danger'
        }
        return statusMap[status]
      },
      chineseFilter(status) {
        const statusMap = {
          published: '发布',
          draft: '草稿',
          deleted: '下架'
        }
        return statusMap[status]
      }
    },
    data() {
      return {
        isInit:false,
        deleteId:-1,
        deleteLoading:false,
        dialogVisible: false,
        status: [{
          value: '',
          label: '全部'
        }, {
          value: 'published',
          label: '发布'
        }, {
          value: 'draft',
          label: '草稿'
        }],
        importance: [{
          value: 0,
          label: '全部'
        }, {
          value: 1,
          label: '普通'
        }, {
          value: 2,
          label: '顶置'
        }, {
          value: 3,
          label: '聚焦'
        }],
        list: null,
        total: 0,
        listLoading: true,
        listQuery: {
          status: '',
          importance: 0,
          context: '',
          page: 1,
          size: 20
        }
      }
    },
    created() {
      this.getList()
    },
    methods: {
      publishedComment: async function(msg) {
        await publisdedComment({id:msg.id}).then(res => {
          if (res.code === 20000) {
            // for(j = 0,len=this.list.length; j < len; j++) {
            //   if (this.list[j].comments != null && this.ist[j].comments.length != 0) {
            //     if (this.list[j].comments[0].id === msg.docId) {
            //       this.list[j].comment += 1;
            //       break;
            //     }
            //   }
            // }
            msg.status = 1;
            this.$notify({
              title: '审核成功',
              message: '评论：\"'+msg.content+'\"通过审核',
              type: 'success',
              duration: 2000
            })
          }
        })
      },
      deleteRow: async function(msg) {
        deleteComment({id:msg.id}).then(res => {
          if (res.code === 20000) {
            // for(j = 0,len=this.list.length; j < len; j++) {
            //   if (this.list[j].comments != null && this.ist[j].comments.length != 0) {
            //     if (this.list[j].comments[0].id === msg.docId && this.list[j].comment > 0) {
            //       this.list[j].comment -= 1;
            //       break;
            //     }
            //   }
            // }
            msg.content = '已删除';
            msg.status = 1;
            this.$notify({
              title: '删除成功',
              message: '评论：\"'+msg.content+'\"已被删除审核',
              type: 'success',
              duration: 2000
            })
          }
        })
       },
      getComment: async function(msg) {
        this.isInit = true;
        await getComment({id:msg.id}).then(res => {
          this.isInit = false;
          if (res.code === 20000) {
            msg.comments = res.data
          }

        }).catch(res => {
            this.isInit = false;
          });
          this.isInit = false;
          console.log(msg.comments)
      },
      beforeDelete(msg) {
        this.deleteId = msg
        this.dialogVisible = true;
        this.deleteLoading = false;
      },
      deleteDoc: async function() {
        this.deleteLoading = true;
        this.dialogVisible = false;
        if (this.deleteId === -1)
          return
        await deleteDoc({id:this.deleteId}).then(res => {
          this.dialogVisible = false;
          this.deleteId = -1;
          this.deleteLoading = false;
        })
        this.deleteId = -1;
        this.deleteLoading = false;
      },
      detail(msg) {
        this.$router.replace('/example/edit/' + msg)
      },
      changeStatus: async function(msg) {

        const data = {
          id: msg.id,
          status: msg.status!='published'?'published':'draft'
        }
        await update(data).then(res => {
          if (res.code === 20000) {
            msg.status = data.status
            this.$notify({
              title: '成功',
              message: msg.status != 'draft' ? '发布《' + msg.title + '》': '下架《' + msg.title + '》',
              type: 'success',
              duration: 2000
            })
          }
        })
      },
      changeComment: async function(msg) {
        if (msg.comment === 0)
          return
        await update({
          id: msg.id,
          comment: msg.comment
        }).then(res => {
          if (res.code === 20000) {
            this.$notify({
              title: '成功',
              message: msg.comment > 0 ? '开放《' + msg.title + '》的评论': '关闭《' + msg.title + '》的评论',
              type: 'success',
              duration: 2000
            })
          }
        })
      },
      getList() {
        this.listLoading = true
        fetchList(this.listQuery).then(response => {
          this.list = response.data.list
          this.total = response.data.total
          this.listLoading = false
        })
      }
    }
  }
</script>

<style scoped>
  .item {
    margin-top: 8px;
    margin-right: 20px;
  }
  .edit-input {
    padding-right: 100px;
  }

  .cancel-btn {
    position: absolute;
    right: 15px;
    top: 10px;
  }
</style>
